<template>
  <view class="tabbar-box py-14rpx" :style="{ height: height, backgroundColor: bgColor }">
    <view class="items" v-for="(item, index) in list" :key="index" @click="toPage(item.url)">
      <!-- 图标 -->
      <view>
        <wd-img
          :width="'80rpx'"
          :height="'80rpx'"
          :src="index === selectedIndex ? item.selectedIconPath : item.icon"
          v-if="index === selectedIndex && item?.selectedNotText"
        />
        <wd-img
          :width="'50rpx'"
          :height="'50rpx'"
          :src="index === selectedIndex ? item.selectedIconPath : item.icon"
          v-else
        />
      </view>

      <!-- 文字 -->
      <text
        :style="{ color: index === selectedIndex ? activeColor : inactiveColor }"
        v-if="!item.selectedNotText || (item.selectedNotText && index !== selectedIndex)"
      >
        {{ item?.title }}
      </text>
    </view>
  </view>
</template>

<script lang="ts" setup>
const props = defineProps({
  list: {
    type: Array as PropType<
      {
        url: string
        title: string
        icon?: string

        selectedIconPath?: string
        selectedNotText?: boolean //选中之后没有文字
      }[]
    >,
    required: true,
  },
  height: {
    type: String,
    default: '110rpx',
  },
  bgColor: {
    type: String,
    default: '#fff',
  },

  activeColor: {
    type: String,
    default: '#FF4600',
  },
  inactiveColor: {
    type: String,
    default: '#ABB7C2',
  },
})
onMounted(() => {
  uni.hideTabBar()
})

const toPage = (url: string) => {
  uni.switchTab({ url })
}

const selectedIndex = ref<number>(0) // 默认没有选中的项

// 获取当前页面的路径
const pages = getCurrentPages()
const currentPage = '/' + pages[pages.length - 1].route

// 比较并找到当前选中的 tabbar 索引
const findSelectedIndex = () => {
  const index = props.list.findIndex((item) => item.url == currentPage)

  selectedIndex.value = index !== -1 ? index : -1
}

// 页面加载时，比较当前页面
findSelectedIndex()
</script>

<style lang="scss" scoped>
.tabbar-box {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 9;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  box-shadow: 0rpx 0rpx 6rpx 0rpx rgba(120, 120, 120, 0.25);
}
.items {
  display: flex;
  flex: 1;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 25rpx;
}
</style>
